package com.sxy.web.filter; /**
 * @author 宋鑫宇
 * @version 1.0
 */

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//登录验证过滤器
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;

        //判断访问资源路径是否和登录注册相关
        String[] urls = {"/login.jsp","/css/","/imgs/","/loginServlet","/register.jsp","/registerServlet","/checkCodeServlet"};
        //获取当前访问的资源路径
        String url = req.getRequestURL().toString();
        //遍历urls数组判断
        for (String s : urls) {
            if (url.contains(s)) {
                //找到了，放行
                chain.doFilter(request, response);
                return;
            }
        }

        //判断session中是否有user数据
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        //判断user是否为null
        if (user == null){
            //没有登录
            req.setAttribute("msg","您还没有登录，请先登录~");
            req.getRequestDispatcher("login.jsp").forward(request, response);
        }else {
            //已经登录
            //放行
            chain.doFilter(request, response);
        }

    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
}
